import React, { useState } from 'react';
import {
  View,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  Image,
  Text
} from 'react-native';
import EmpyData from './EmpyData';
import FooterLoadMore from './FooterLoadMore';

const SearchList = (props) => {
  const { navigation, data } = props;
  const [refresh, setRefresh] = useState(false);
  const [loadMore, setLoadMore] = useState(false);

  const renderContentItem = ({ item, index }) => {
    return (
      <TouchableOpacity activeOpacity={0.9} key={Math.random()} >
        <View key={Math.random()} style={[styles.box, index % 2 == 0 && styles.boxSingle]}>
          <Image style={styles.boxImg} source={item.img} />
          <Text style={styles.boxTitle} ellipsizeMode="tail" numberOfLines={2}>{item.title}</Text>
          <Text style={styles.boxPrice} >￥{item.price}</Text>
        </View>
      </TouchableOpacity>
    )
  }

  const onRefresh = () => {
    setRefresh(true);
    setTimeout(() => {
      setRefresh(false);
    }, 2000)
  }

  const onEndReached = () => {
    setLoadMore(true)
    setTimeout(() => {
      setLoadMore(false);
    }, 2000)
  }

  return (
    <FlatList
      data={data}
      numColumns={2}
      ListEmptyComponent={() => <EmpyData />}
      ListFooterComponent={() => loadMore ? <FooterLoadMore /> : null}
      renderItem={renderContentItem}
      keyExtractor={() => Math.random()}
      refreshing={refresh}
      onRefresh={() => onRefresh()}
      onEndReachedThreshold={0.1}
      onEndReached={() => onEndReached()}
      showsHorizontalScrollIndicator={false}
    />
  )
}

const styles = StyleSheet.create({
  box: {
    width: 160,
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    flexDirection: 'column',
    marginBottom: 18
  },
  boxSingle: {
    marginRight: 14
  },
  boxImg: {
    width: 160,
    height: 262,
    borderRadius: 4
  },
  boxTitle: {
    fontSize: 14,
    marginTop: 17,
    lineHeight: 20,
    height: 40,
    color: '#000'
  },
  boxPrice: {
    fontSize: 21,
    lineHeight: 31,
    color: '#000'
  },
})

export default SearchList;